"""
Gua框架日志系统使用示例
基于Linus设计哲学的极简日志实现
"""

import asyncio
import time
from gua import GuaApp, GuaLogger, LoggingMiddleware, SimpleMonitor

# 创建应用
app = GuaApp()

# 配置日志记录器
logger = GuaLogger("demo_app", output="console")  # 可选: "console", "file", "json"

# 创建性能监控器
monitor = SimpleMonitor(logger)

# 添加日志中间件
app.use(LoggingMiddleware(logger, slow_threshold=0.5))


@app.route("/")
async def home():
    """首页 - 基础日志记录"""
    logger.info("user_visited_home", user_agent="demo")
    return {"message": "Hello World", "version": "1.0"}


@app.route("/slow")
async def slow_request():
    """慢请求示例 - 自动检测慢请求"""
    logger.info("slow_request_started")
    await asyncio.sleep(1.0)  # 模拟慢操作
    logger.info("slow_request_completed", duration=1.0)
    return {"message": "This was a slow request"}


@app.route("/error")
async def error_request():
    """错误处理示例 - 自动记录错误"""
    logger.info("error_request_started")
    # 故意引发错误
    raise ValueError("This is a demo error")


@app.route("/custom")
async def custom_logging():
    """自定义日志示例"""
    # 记录用户行为
    logger.info("user_action", user_id="123", action="login", ip="192.168.1.1")

    # 记录警告
    logger.warn("high_memory_usage", memory_mb=512, threshold_mb=400)

    # 记录业务数据
    logger.debug(
        "database_query", table="users", query="SELECT * FROM users", duration=0.05
    )

    return {"message": "Custom logging demo"}


@app.route("/stats")
async def stats():
    """性能统计API"""
    return monitor.get_stats()


@app.route("/json-logs")
async def json_logs_demo():
    """JSON格式日志示例"""
    # 创建JSON格式的日志记录器
    json_logger = GuaLogger("json_demo", output="json")

    # 记录结构化日志
    json_logger.info(
        "api_call",
        endpoint="/json-logs",
        method="GET",
        user_id="user123",
        request_id="req-456",
        timestamp=time.time(),
    )

    return {"message": "JSON logging demo"}


# WebSocket示例
@app.websocket("/ws")
async def websocket_handler(scope, receive, send):
    """WebSocket日志示例"""
    logger.info("websocket_connection_established", path="/ws")

    try:
        # 等待连接建立
        message = await receive()
        if message["type"] == "websocket.connect":
            await send({"type": "websocket.accept"})
            logger.info("websocket_accepted")

        # 处理消息
        for i in range(3):
            await send({"type": "websocket.send", "text": f"Message {i + 1}"})
            logger.debug("websocket_message_sent", message_id=i + 1)
            await asyncio.sleep(0.5)

        # 关闭连接
        await send({"type": "websocket.close"})
        logger.info("websocket_closed_gracefully")

    except Exception as e:
        logger.error("websocket_error", error=str(e))
        await send({"type": "websocket.close", "code": 1011})


if __name__ == "__main__":
    import subprocess
    import sys
    
    # 使用gua命令显示示例启动信息
    result = subprocess.run([sys.executable, "-m", "gua.cli", "examples.logging_demo:app", "--example-info"],
                          capture_output=True, text=True)
    if result.returncode == 0:
        print(result.stdout)
    else:
        print("错误: 无法显示启动信息")
        print("请手动运行: gua examples.logging_demo:app --example-info")
